import 'package:flutter/material.dart';

class SecuritySettingsPage extends StatefulWidget {
  const SecuritySettingsPage({super.key});

  @override
  State<SecuritySettingsPage> createState() => _SecuritySettingsPageState();
}

class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
  bool _pushNotificationEnabled = true;
  bool _emailNotificationEnabled = true;
  bool _smsNotificationEnabled = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('安全设置'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildSectionTitle('账户安全'),
            _buildSecurityCard(
              icon: Icons.lock,
              title: '修改密码',
              subtitle: '定期更换密码保护账户安全',
              onTap: () => _showChangePasswordDialog(),
            ),
            _buildSecurityCard(
              icon: Icons.email,
              title: '绑定邮箱',
              subtitle: '当前邮箱：zhangsan@example.com',
              onTap: () => _showBindEmailDialog(),
            ),
            _buildSecurityCard(
              icon: Icons.phone,
              title: '绑定手机',
              subtitle: '当前手机：138****8000',
              onTap: () => _showBindPhoneDialog(),
            ),
            const SizedBox(height: 20),
            _buildSectionTitle('登录设备'),
            _buildSecurityCard(
              icon: Icons.devices,
              title: '登录设备管理',
              subtitle: '管理已登录的设备',
              onTap: () => _showDeviceManagementDialog(),
            ),
            const SizedBox(height: 20),
            _buildSectionTitle('通知设置'),
            _buildSwitchCard(
              icon: Icons.notifications,
              title: '推送通知',
              subtitle: '接收重要消息推送',
              value: _pushNotificationEnabled,
              onChanged: (value) {
                setState(() {
                  _pushNotificationEnabled = value;
                });
              },
            ),
            _buildSwitchCard(
              icon: Icons.email_outlined,
              title: '邮件通知',
              subtitle: '接收邮件提醒',
              value: _emailNotificationEnabled,
              onChanged: (value) {
                setState(() {
                  _emailNotificationEnabled = value;
                });
              },
            ),
            _buildSwitchCard(
              icon: Icons.sms,
              title: '短信通知',
              subtitle: '接收短信提醒',
              value: _smsNotificationEnabled,
              onChanged: (value) {
                setState(() {
                  _smsNotificationEnabled = value;
                });
              },
            ),
            const SizedBox(height: 20),
            _buildSectionTitle('隐私设置'),
            _buildSecurityCard(
              icon: Icons.visibility,
              title: '在线状态',
              subtitle: '设置在线状态可见性',
              onTap: () => _showOnlineStatusDialog(),
            ),
            _buildSecurityCard(
              icon: Icons.location_on,
              title: '位置信息',
              subtitle: '设置位置信息可见性',
              onTap: () => _showLocationPrivacyDialog(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: Colors.grey,
        ),
      ),
    );
  }

  Widget _buildSecurityCard({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            icon,
            color: Theme.of(context).primaryColor,
            size: 24,
          ),
        ),
        title: Text(
          title,
          style: const TextStyle(
            fontWeight: FontWeight.w500,
          ),
        ),
        subtitle: Text(
          subtitle,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
        trailing: const Icon(Icons.arrow_forward_ios, size: 16),
        onTap: onTap,
      ),
    );
  }

  Widget _buildSwitchCard({
    required IconData icon,
    required String title,
    required String subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(
            icon,
            color: Theme.of(context).primaryColor,
            size: 24,
          ),
        ),
        title: Text(
          title,
          style: const TextStyle(
            fontWeight: FontWeight.w500,
          ),
        ),
        subtitle: Text(
          subtitle,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
        trailing: Switch(
          value: value,
          onChanged: onChanged,
          activeColor: Theme.of(context).primaryColor,
        ),
      ),
    );
  }

  void _showChangePasswordDialog() {
    final TextEditingController currentPasswordController =
        TextEditingController();
    final TextEditingController newPasswordController = TextEditingController();
    final TextEditingController confirmPasswordController =
        TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('修改密码'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: currentPasswordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: '当前密码',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: newPasswordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: '新密码',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: confirmPasswordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: '确认新密码',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 这里应该验证密码并调用API
              Navigator.pop(context);
              _showSuccessMessage('密码修改成功');
            },
            child: const Text('确认修改'),
          ),
        ],
      ),
    );
  }

  void _showBindEmailDialog() {
    final TextEditingController emailController = TextEditingController();
    final TextEditingController codeController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('绑定邮箱'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: emailController,
              keyboardType: TextInputType.emailAddress,
              decoration: const InputDecoration(
                labelText: '邮箱地址',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: codeController,
                    decoration: const InputDecoration(
                      labelText: '验证码',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: () {
                    // 发送验证码
                    _showSuccessMessage('验证码已发送');
                  },
                  child: const Text('发送'),
                ),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _showSuccessMessage('邮箱绑定成功');
            },
            child: const Text('确认绑定'),
          ),
        ],
      ),
    );
  }

  void _showBindPhoneDialog() {
    final TextEditingController phoneController = TextEditingController();
    final TextEditingController codeController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('绑定手机'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: phoneController,
              keyboardType: TextInputType.phone,
              decoration: const InputDecoration(
                labelText: '手机号码',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: codeController,
                    decoration: const InputDecoration(
                      labelText: '验证码',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: () {
                    _showSuccessMessage('验证码已发送');
                  },
                  child: const Text('发送'),
                ),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _showSuccessMessage('手机绑定成功');
            },
            child: const Text('确认绑定'),
          ),
        ],
      ),
    );
  }

  void _showDeviceManagementDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('登录设备管理'),
        content: SizedBox(
          width: double.maxFinite,
          height: 300,
          child: Column(
            children: [
              const Text('当前登录设备：'),
              const SizedBox(height: 16),
              Expanded(
                child: ListView(
                  children: [
                    _buildDeviceItem(
                      'iPhone 14',
                      '192.168.1.100',
                      '2024-01-15 14:30',
                      true,
                    ),
                    _buildDeviceItem(
                      'MacBook Pro',
                      '192.168.1.101',
                      '2024-01-14 09:15',
                      false,
                    ),
                    _buildDeviceItem(
                      'iPad Air',
                      '192.168.1.102',
                      '2024-01-13 16:45',
                      false,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  Widget _buildDeviceItem(
      String device, String ip, String time, bool isCurrent) {
    return ListTile(
      leading: Icon(
        isCurrent ? Icons.phone_iphone : Icons.computer,
        color: isCurrent ? Colors.green : Colors.grey,
      ),
      title: Text(device),
      subtitle: Text('$ip\n$time'),
      trailing: isCurrent
          ? const Chip(
              label: Text('当前设备'),
              backgroundColor: Colors.green,
              labelStyle: TextStyle(color: Colors.white),
            )
          : TextButton(
              onPressed: () {
                // 下线设备
                _showSuccessMessage('设备已下线');
              },
              child: const Text('下线'),
            ),
    );
  }

  void _showOnlineStatusDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('在线状态设置'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            RadioListTile<String>(
              title: const Text('所有人可见'),
              value: 'all',
              groupValue: 'all',
              onChanged: (value) {
                Navigator.pop(context);
                _showSuccessMessage('设置已保存');
              },
            ),
            RadioListTile<String>(
              title: const Text('好友可见'),
              value: 'friends',
              groupValue: 'all',
              onChanged: (value) {
                Navigator.pop(context);
                _showSuccessMessage('设置已保存');
              },
            ),
            RadioListTile<String>(
              title: const Text('仅自己可见'),
              value: 'none',
              groupValue: 'all',
              onChanged: (value) {
                Navigator.pop(context);
                _showSuccessMessage('设置已保存');
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  void _showLocationPrivacyDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('位置信息设置'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            RadioListTile<String>(
              title: const Text('所有人可见'),
              value: 'all',
              groupValue: 'all',
              onChanged: (value) {
                Navigator.pop(context);
                _showSuccessMessage('设置已保存');
              },
            ),
            RadioListTile<String>(
              title: const Text('好友可见'),
              value: 'friends',
              groupValue: 'all',
              onChanged: (value) {
                Navigator.pop(context);
                _showSuccessMessage('设置已保存');
              },
            ),
            RadioListTile<String>(
              title: const Text('不显示位置'),
              value: 'none',
              groupValue: 'all',
              onChanged: (value) {
                Navigator.pop(context);
                _showSuccessMessage('设置已保存');
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  void _showSuccessMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }
}
